package com.logos.ruralrevitalization.service.impl;

import ch.qos.logback.classic.turbo.TurboFilter;
import com.logos.ruralrevitalization.converter.ShoppingCartConverter;
import com.logos.ruralrevitalization.entity.ShoppingCart;
import com.logos.ruralrevitalization.enums.IsDeleteFlagEnum;
import com.logos.ruralrevitalization.mapper.AgriculturalProductMapper;
import com.logos.ruralrevitalization.mapper.ShoppingCartMapper;
import com.logos.ruralrevitalization.req.ShoppingCartReq;
import com.logos.ruralrevitalization.resp.AgriculturalProductResp;
import com.logos.ruralrevitalization.service.ShoppingCartService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 农产品购物车表(ShoppingCart)表服务实现类
 *
 * @author rose
 * @since 2025-03-26 08:59:58
 */
@Service("shoppingCartService")
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private AgriculturalProductMapper agriculturalProductMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ShoppingCart queryById(Long id) {
        return this.shoppingCartMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param shoppingCart 筛选条件
     * @param pageRequest  分页对象
     * @return 查询结果
     */
    @Override
    public Page<ShoppingCart> queryByPage(ShoppingCart shoppingCart, PageRequest pageRequest) {
        long total = this.shoppingCartMapper.count(shoppingCart);
        return new PageImpl<>(this.shoppingCartMapper.queryAllByLimit(shoppingCart, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param shoppingCart 实例对象
     * @return 实例对象
     */
    @Override
    public ShoppingCart insert(ShoppingCart shoppingCart) {
        this.shoppingCartMapper.insert(shoppingCart);
        return shoppingCart;
    }

    /**
     * 修改数据
     *
     * @param shoppingCart 实例对象
     * @return 实例对象
     */
    @Override
    public ShoppingCart update(ShoppingCart shoppingCart) {
        this.shoppingCartMapper.update(shoppingCart);
        return this.queryById(shoppingCart.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.shoppingCartMapper.deleteById(id) > 0;
    }

    @Override
    public Boolean add(ShoppingCartReq shoppingCartReq) {
        // 先查询是否存在购物车数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setProductId(shoppingCartReq.getProductId());
        shoppingCart.setUserId(shoppingCartReq.getUserId());
        shoppingCart.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.queryByCondition(shoppingCart);
        if (!shoppingCarts.isEmpty()) {
            // 如果存在，则修改数量
            int newCount = shoppingCarts.get(0).getQuantity() + shoppingCartReq.getQuantity();
            shoppingCart.setQuantity(newCount);
            shoppingCart.setId(shoppingCarts.get(0).getId());
            shoppingCartMapper.update(shoppingCart);
            return true;
        }
        shoppingCart = ShoppingCartConverter.INSTANCE.convertReqToEntity(shoppingCartReq);
        if (shoppingCartMapper.insert(shoppingCart) > 0) {
            return true;
        }
        return null;
    }

    @Override
    public Boolean deleteById(ShoppingCartReq shoppingCartReq) {
        ShoppingCart shoppingCart = ShoppingCartConverter.INSTANCE.convertReqToEntity(shoppingCartReq);
        shoppingCart.setIsDeleted(IsDeleteFlagEnum.DELETED.getCode());
        if (shoppingCartMapper.update(shoppingCart) > 0) {
            return true;
        }
        return null;
    }

    @Override
    public List<AgriculturalProductResp> queryByUserId(Long userId) {
        // 首先查询出于该用户关联的购物车数据 user_id = userId and is_deleted = 0
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        shoppingCart.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.queryByCondition(shoppingCart);
        // 通过product_id 查询农产品信息
        Map<Long, Integer> idsAndCount = new HashMap<>();
        Map<Long,Long> prodIdsAndShopIds = new HashMap<>();
        List<Long> ids = new LinkedList<>();
        for (ShoppingCart tmp : shoppingCartList) {
            Long productId = tmp.getProductId();
            idsAndCount.put(productId, tmp.getQuantity());
            ids.add(productId);
            prodIdsAndShopIds.put(tmp.getProductId(),tmp.getId());
        }
        // 查询出每个农产品购物车的数量
        if (ids == null || ids.isEmpty()) {
            return null;
        }
        List<AgriculturalProductResp> agriculturalProductRespList = agriculturalProductMapper.queryByProductIds(ids);
        agriculturalProductRespList.forEach(item -> {
            item.setQuantity(idsAndCount.get(item.getId()));
            item.setShoppingCartId(prodIdsAndShopIds.get(item.getId()));
        });
        return agriculturalProductRespList;
    }

    @Override
    public Boolean deleteAll(Long userId) {
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        shoppingCart.setIsDeleted(IsDeleteFlagEnum.DELETED.getCode());
        shoppingCartMapper.clear(shoppingCart);
        return true;
    }
}
